<?php

abstract class Abstracts extends CI_Model{
	
	protected $_db;
	
	protected $_table;
	
	protected function query($sql){
		return 	$this->_db->query($sql);	
	}
	public function __construct(){
		$this->_db = $this->db;
	}
	public function getTable(){
		return $this->_table;
	}
	
	public function getId(){
		//$re = $this->_db->query("insert into auto_id Values()");
		return $this->_db->insert_id();
	}
	/**
	 * @todo 插入一条记录
	 * @param unknown_type $data =>array('col'=>value);
	 * @return boolean
	 */
	public function insert($data){
		if(is_array($data)){
			$fields = $this->_db->list_fields($this->_table);
			$sql    = "insert into {$this->_table} set ";
			$setArr = array(); 
			foreach($data as $k=>$v){
				if(in_array($k,$fields)){
					$setArr[] = "$k = '{$v}'";
				}
			}			
			if(!empty($setArr)){
				$sql .= implode(",", $setArr);
				return $this->_db->query($sql);
			}	
		}
		return false;
	}
	/**
	 * @todo 查询一条记录
	 * @param unknown_type $sql
	 * @return multitype:
	 */
	public function getRow($sql){
		$query = $this->_db->query($sql);
		$row   = array();
		if ($query->num_rows() > 0){
			$row = $query->row_array();				
		}
		return $row;
	}
	
	public function getAll($sql){
		$query = $this->_db->query($sql);
		return $query->result_array();
	}
	
	public function update($data,$where=null){	
		if(!$where && isset($data['id'])){			
			$where = " id = '{$data['id']}'";
			unset($data['id']);					
		}
		if(!is_string($where) || empty($data))
			return false;		
		$fields = $this->_db->list_fields($this->_table);
		$sql    = "update {$this->_table} set ";
		$setArr = array();
		foreach($data as $k=>$v){
			if(in_array($k,$fields)){
				$setArr[] = "$k = '{$v}'";
			}
		}
		
		if(!empty($setArr)){
			$sql .= implode(",", $setArr) . ($where?" where ".$where:"");			
			return $this->_db->query($sql);
		}
		
		return false;
	}
	/**
	 * 删除数据
	 * @param unknown_type $cond 为数据记录ID或者where语句
	 * @return boolean
	 */
	public function delete($cond){
		if(!$cond)
			return false;
		if(is_numeric($cond))
			$sql = "delete from {$this->_table} where id = '$cond'";
		else
			$sql = "delete from {$this->_table} where $cond";
		return $this->_db->query($sql);
	}
	public function getCount($where){		
		$sql = "select count(id) as c from {$this->_table}";
		$sql .= $where? " where ".$where:""; 
		$re   = $this->getRow($sql);
		return isset($re['c'])?$re['c']:0;
	}
}